<template>
	<view style="width: 100%;height: 100vh;position: relative;overflow: hidden;">
		<image src="../static/background2.jpg" style="height: 100vh;width: 100%;position: absolute;left: 0%;top: 0%;">
		</image>
		<view class='container bg-gray'>
			<tn-nav-bar bgClass="bg-gradual-blue2">
				<view>
					{{ bleName }}
				</view>
			</tn-nav-bar>
			<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
				<view class="padding-sm padding-bottom-xs flex justify-between">
					<view class="flex align-center">
						<image src="/static/img/ble/ble.png" style="width: 50rpx;height: 42rpx;"></image>
						<text class="padding-left-xs text-bold text-xl" style="color: #0081ff;">已连接</text>
						<text class="margin-left cuIcon-clothes tn-text-xxl" style="color: #0081ff;" @click="setImg" />
					</view>
					<view class="flex">
						<acqui-dynamic-message :messageList="PackInfo['Protect'].tValue?PackInfo['Protect'].tValue:[]"
							ref="dynamicMessage"></acqui-dynamic-message>
					</view>
				</view>

				<view class="margin-sm tn-flex tn-flex-row-center"
					style="align-items: center;flex-direction: column;margin-bottom: 0;">

					<view style="justify-content: center;">
						<image class="tn-flex-row-center" :src="carImgs[imgNum]" @click="toConfig"></image>
					</view>
					<view class="tn-margin"
						style="height: 365px;width: 100%;margin-top: -80px;border-radius: 30rpx; background-color: rgb(255 255 255 / 70%);">
						<view class="tn-flex" style="margin-top: 80px;width: 100%;height: 140px;">
							<view class="tn-flex-basic-md tn-margin b-card tn-margin-right-xs">
								<view
									class="tn-flex tn-flex-row-between tn-flex-col-bottom tn-text-bold text-xxl text-black tn-margin-sm">
									<text class="">{{PackInfo['SOC'].tValue?PackInfo['SOC'].tValue: 0}} %</text>
									<text class="text-gray text-lg" style="letter-spacing: 1px">剩余电量</text>
								</view>
								<zuBattery showPercent
									:status="PackInfo['Status'].tValue?PackInfo['Status'].tValue.status:0"
									v-if="!isCharging" :battery="PackInfo['SOC'].tValue" height='80rpx' width="260rpx">
								</zuBattery>
								<zuBattery v-else ref='zuBattery' :battery="SOCValue" height='80rpx' width="260rpx">
								</zuBattery>

							</view>
							<view class="tn-flex-basic-md tn-margin tn-margin-left-sm b-card text-black text-bold ">
								<view class="tn-flex tn-flex-direction-column ">
									<view class="tn-flex  tn-flex-row-center tn-flex-col-center"
										style="height: 105rpx;">
										<text class="tn-icon-light-fill text-lg padding-xs"> </text>
										<text class="padding-right text-bold text-xl" style="letter-spacing: 2px">
											充电</text>
										<switch class="radius" @change='e=>mosBtnComfig(e,"A510")'
											:class="B_CONFIG['CHG_EN'].tValue?(B_CONFIG['CHG_EN'].tValue*1===1?'checked':''):''"
											:checked="B_CONFIG['CHG_EN'].tValue?(B_CONFIG['CHG_EN'].tValue*1===1?true:false):false">
										</switch>
									</view>
									<view class="tn-flex  tn-flex-row-center tn-flex-col-center"
										style="height: 105rpx;">
										<text class="tn-icon-logout text-lg padding-xs"></text>
										<text class="padding-right text-bold text-xl" style="letter-spacing: 2px">
											放电</text>
										<switch class="radius" @change='e=>mosBtnComfig(e,"A511")'
											:class="B_CONFIG['DSG_EN'].tValue?(B_CONFIG['DSG_EN'].tValue*1===1?'checked':''):''"
											:checked="B_CONFIG['DSG_EN'].tValue?(B_CONFIG['DSG_EN'].tValue*1===1?true:false):false">
										</switch>
									</view>
								</view>
							</view>

						</view>
						<view class="margin-lr margin-bottom b-card">
							<view class="grid col-3 flex justify-center padding-top">
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2 text-bold ">
										{{ PackInfo.Voltage.tValue?PackInfo.Voltage.tValue:0 }} V
									</view>
									<view>电池电压</view>
								</view>
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2 text-bold ">
										{{ PackInfo.CurCadc.tValue?PackInfo.CurCadc.tValue: '0.0' }} A
									</view>
									<view>当前电流</view>
								</view>
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2 text-bold ">
										{{PackInfo.FCC.tValue?PackInfo.FCC.tValue: '0.0'}} AH
									</view>
									<view>满冲容量</view>
								</view>
							</view>
							<view class="grid col-3 flex justify-center padding-tb">
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2  text-bold ">
										{{PackInfo.PowerW.tValue?PackInfo.PowerW.tValue: '0.0'}} W
									</view>
									<view>运行功率</view>
								</view>
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2  text-bold ">
										{{(PackInfo.BalC.tValue? (PackInfo.BalC.tValue / 1000) : '0.0') }} A
									</view>
									<view>均衡电流</view>
								</view>
								<view class="flex flex-direction align-center justify-center">
									<view class="text-blue2  text-bold ">
										{{ (PackInfo.TOTALKWH_H.tValue?PackInfo.TOTALKWH_H.tValue*1:0 << 8) | (PackInfo.TOTALKWH_L.tValue?PackInfo.TOTALKWH_L.tValue*1:0) }}
										KWH
									</view>
									<view>总电量</view>
								</view>
							</view>
						</view>
					</view>

				</view>




				<view class="margin-sm radius-25" style="margin-top: 0;box-shadow: 2rpx 2rpx 4rpx 4rpx #def4f9;">
					<tn-collapse arrowColor='#0081ff'>
						<tn-collapse-item ref='collapse_1' icon='tn-icon-temperature-c' title="温度"
							subTitle='temperature'>
							<view class="cu-card tn-flex tn-flex-basic-sm tn-flex-direction-row">
								<view class="tn-flex justify-center align-center">
									<image src="/static/img/ble/wd.png" style="width: 128px;max-height: 128px;"
										mode="" />
								</view>
								<view class="tn-flex tn-flex-basic-lg tn-flex-direction-column">
									<view
										class="tn-flex margin-lr-sm padding-tb  shadow solid-bottom  justify-around tn-flex-direction-row">
										<view>
											<text class="text-bold">MOS</text>
											<text class="padding-left-xs text-bold text-blue2">
												{{PackInfo.T_MOS.tValue?PackInfo.T_MOS.tValue: '0.0'}} ℃
											</text>
										</view>
										<view>
											<text class="text-bold">均衡</text>
											<text class="padding-left-xs text-bold text-blue2">
												{{PackInfo.T_BAL.tValue?PackInfo.T_BAL.tValue: '0.0'}} ℃
											</text>
										</view>
									</view>
									<view class="grid col-2">
										<view style="display: flex; justify-content: center;"
											v-for="(item ,index) in PackInfo.TempNum.tValue?PackInfo.TempNum.tValue:0"
											:key="index">
											<view class="margin-tb-sm">
												<view
													style="display: flex; justify-content: space-around;align-items: center;flex-direction: column;width: 100%;height: 100%;padding: 5px;">
													<view class="text-bold text-blue2">
														{{TempInfo['TEMP'+(item+1)].tValue}} ℃
													</view>
													<view class="text-sm">温度 {{item+1}}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</tn-collapse-item>
					</tn-collapse>
				</view>



				<view class="margin-sm radius-25" style="box-shadow: 2rpx 2rpx 4rpx 4rpx #def4f9;">
					<tn-collapse arrowColor='#0081ff'>
						<tn-collapse-item ref='collapse_2' icon="tn-icon-down-circle-simple" title="电芯电压"
							subTitle='Voltage'>
							<view class="margin-sm grid col-2" style="min-height: 40px;">
								<template v-for="(item , index) in PackInfo.CellNum.tValue?PackInfo.CellNum.tValue:0">
									<view :key="index" class="margin-xs "
										style="display: flex; justify-content: space-around;width: 160px;">
										<view class="cu-capsule radius text-lg">
											<view class='cu-tag  '
												:class="(PackInfo.Vmax.tValue===VCellInfo['VCELL'+(item+1)].tValue)?'bg-orange':(PackInfo.Vmin.tValue===VCellInfo['VCELL'+(item+1)].tValue?'bg-green':'bg-blue')"
												style="width: 65px;">
												电芯{{(item+1)}}
											</view>
											<view class="cu-tag line-blue">
												{{VCellInfo['VCELL'+(item+1)].tValue}} mV
											</view>
										</view>
									</view>

								</template>

							</view>
						</tn-collapse-item>
					</tn-collapse>
				</view>


				<view class="cu-list menu margin-sm  radius-25" style="box-shadow: 2rpx 2rpx 4rpx 4rpx #def4f9;">
					<view class="flex">
						<view class="flex-sub margin-lr-xs bg-white">
							<view class="cu-item padding-lr-sm" style="background: none;padding: 10px 10px 10px 20px;">
								<view class="content text-blue2">
									<view class="text-xl text-bold" style="letter-spacing: 1px;">一键强启</view>
									<view class="text-sm text-gray" style="height: 38px;">电池启动后，2分钟内将自动关闭。</view>
								</view>
								<view class="action flex action justify-end">
									<button class="cu-btn  cuIcon bg-blue shadow" @click="sendDoubleCmd">
										<text class="tn-icon-power  tn-text-lg-xxl" style=""></text>
									</button>
								</view>
							</view>
						</view>
						<view class="flex-sub margin-lr-xs bg-white">
							<view class="cu-item padding-lr-sm" style="background: none;padding: 10px 10px 10px 20px;">
								<view class="content text-blue2">
									<view class="text-xl text-bold" style="letter-spacing: 1px;">系统重启</view>
									<view class="text-sm text-gray" style="height: 38px;">电池断电重新启动</view>
								</view>
								<view class="flex action justify-end">
									<button class="cu-btn  cuIcon bg-blue shadow" @click="sendRestartCmd">
										<text class="tn-icon-refresh  tn-text-lg-xxl" style=""></text>
									</button>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view style="height: 10vh;background: none;"></view>
			</view>

		</view>
	</view>

</template>

<script>
	import {
		getProfile
	} from '@/api/modules/common.js'
	import {
		getToken
	} from "@/common/storage/auth.js"
	import {
		getLastOTA
	} from '@/api/modules/device.js'
	import utils from '@/common/utils/utils.js';
	import BLE from "@/libs/bluetooth/BLE.js";
	import Protocol from "@/libs/protocol/tianyi/protocol.js";
	import bleData from "@/libs/protocol/tianyi/bleData.js";
	import zuBattery from '../components/zu-battery/zu-battery'
	// import car from '@/pages_ble/static/2.jpg'
	import car from '@/pages_ble/static/car.png'
	import san from '@/pages_ble/static/san.png'
	import san2 from '@/pages_ble/static/san2.png'
	import one from '@/pages_ble/static/2.jpg'


	import projectConfig from '@/api/config.js';

	let _self;

	let timer = null
	let sendTimer = null
	let changingTimer = null
	const CMDs = [{
		name: 'PACK',
		cmd: '0103a000002f2616'
	}, {
		name: 'VCELL',
		cmd: '0103a1000018663c'
	}, {
		name: 'TEMP',
		cmd: '0103a3000004664d'
	}, {
		name: 'B_CONFIG', //基础参数
		cmd: '0103A50000146709'
	}, {
		name: 'VERSION',
		cmd: '0103A4000008673C'
	}]

	// OTA  status状态字段定义
	// AWAIT(0, "等待升级","未推送固件到设备"),
	// SEND(1, "已发送","已发送设备"),
	// REPLY(2, "升级中","设备OTA升级中"),
	// SUCCESS(3, "成功","升级成功"),
	// FAILED(4, "失败","升级失败"),
	// STOP(5, "停止","设备离线停止推送"),
	// UNKNOWN(404, "未知","未知错误码");

	export default {
		components: {
			zuBattery
		},
		data() {
			return {
				imgNum: 0,
				isFirstLoad: true,
				bleName: null,
				userLevels: {},
				deviceInfo: {},
				PackInfo: bleData.packInfo,
				VCellInfo: bleData.VCellInfo,
				TempInfo: bleData.TempInfo,
				B_CONFIG: bleData.B_CONFIG,
				allConfigParam: {
					...bleData.C_CONFIG,
					...bleData.Cali_CONFIG,
					...bleData.Bal_Sleep,
					...bleData.B_CONFIG
				},
				showPasswordCount: 0,
				isWrite: false,
				isSendCmd: false,
				isCharging: false,
				sendEnable: false,
				readIndex: 0,
				SOCValue: 0,
				//OTA升级参数
				packVersion: null,
				lastOTA: {},
				otaFile: {},
				ota: {
					taskId: 0,
					progress: 0,
					status: 2, // 1 接收文件 2升级中 3升级完成
					version: ''
				},
				carImgs: [one, car, san, san2],
				carImg: car,
			}
		},
		onLoad(options) {
			_self = this
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			if (options.name) {
				this.bleName = options.name
			} else {
				this.bleName = getApp().globalData.bleObj.name
			}
			var that = this;
			that.isWrite = false;
			that.readIndex = 0;

			// 获取用户等级密码信息
			this.$api.common.listUserLevel().then(res => {
				this.userLevels = {}
				if (res.code === 200) {
					for (var i = 0; i < res.data.length; i++) {
						let t = res.data[i]
						this.userLevels['level.' + t.configKey.split('level.')[1]] = t.configValue
					}
				}
			})

			this.$api.device.getLastOTA(this.bleName).then(res => {
				if (res.code === 200) {
					this.lastOTA = res.data
					//判断版本号
					if (this.lastOTA && this.lastOTA.version) {
						setTimeout(() => {
							if (_self.packVersion !== _self.lastOTA.version) {
								BLE.confirm("发现新固件是否开始升级？", async () => {
									const fileTemp = await downloadFile(_self.lastOTA.filePath)
									const fsm = uni.getFileSystemManager();
									try {
										_self.otaFile = fsm.readFileSync(fileTemp
											.tempFilePath);
										console.log('文件字节:', _self.otaFile.byteLength);
									} catch (e) {
										console.error('读取失败:', e);
									}
									console.log('');
								}, "固件升级")
							}
						}, 5000)
					}
				}
			})

		},
		onShow() {
			if (!getApp().globalData.bleObj.state && getApp().globalData.bleObj.deviceId) {
				BLE.Connect(getApp().globalData.bleObj.deviceId, () => {})
			}
			let that = this
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}

			//设置值更改函数
			that.SetValueChanged();
			this.isWrite = false
			that.sendFirstToBle()
			//定时读取蓝牙数据
			timer = setInterval(() => {
				that.sendFirstToBle()
				that.showPasswordCount = 0
			}, 2000)

			//定时发送数据到服务器
			sendTimer = setInterval(() => {
				that.sendDataToMqtt()
			}, 1000)

			const deviceId = that.bleName ? that.bleName : getApp().globalData.bleObj.name;
			console.log('deviceId', deviceId);
			this.getMqttInfo(deviceId)

		},
		onHide() {
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			this.isWrite = false
			this.endMqtt()
		},
		onUnload() {
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			// if (getApp().globalData.bleObj.state) {
			// 	BLE.Close()
			// }
			this.endMqtt()
		},
		mounted() {},
		methods: {
			setImg() {
				_self.imgNum += 1
				if (_self.imgNum > 3) {
					_self.imgNum = 0
				}
			},
			sendRestartCmd() {
				BLE.confirm('是否发送重启指令？', () => {
					Protocol.writeToWrite('A900', Protocol.encryption('A900', 1), async () => {
						console.log('发送指令成功');
						_self.$tn.message.toast('指令下发成功')
						setTimeout(() => {
							_self.isSendCmd = false
						}, 500)
					})
				})
			},
			sendDoubleCmd() {
				_self.isSendCmd = true
				_self.isWrite = false
				_self.readIndex = -1
				BLE.confirm('是否发送强启指令？', () => {
					Protocol.writeToWrite('A510', Protocol.encryption('A510', 1), async () => {
						Protocol.writeToWrite('A511', Protocol.encryption('A511', 1), async () => {
							console.log('发送指令成功');
							_self.$tn.message.toast('指令下发成功')
							setTimeout(() => {
								_self.isSendCmd = false
							}, 500)
						})
					})
				})

			},
			mosBtnComfig(e, address) {
				_self.isSendCmd = true
				_self.isWrite = false
				_self.readIndex = -1
				let v = e.target.value ? 1 : 0
				Protocol.writeToWrite(address, Protocol.encryption(address, v), async () => {
					console.log('发送指令成功');
					_self.$tn.message.toast('指令下发成功')
					setTimeout(() => {
						_self.isSendCmd = false
					}, 500)
				})
			},
			toConfig() {
				this.showPasswordCount += 1;
				if (this.showPasswordCount > 3) {
					uni.navigateTo({
						url: '/pages_ble/ble/tianyi/config'
					})
				}
			},
			startChangeing(chStatus) {
				if (chStatus * 1 === 2) {
					if (changingTimer === null && _self.isCharging === false) {
						changingTimer = setInterval(() => {
							_self.isCharging = true
							_self.SOCValue += 10;
							if (_self.SOCValue >= 106) {
								_self.SOCValue = 5
							}
						}, 1500)
					}
				} else {
					_self.isCharging = false
					if (changingTimer != null) {
						clearInterval(changingTimer)
						changingTimer = null
					}
				}
			},
			sendDataToMqtt() {
				let that = this
				var state = getApp().globalData.bleObj.state;
				if (that.sendEnable && state) {
					let messages = []
					for (let key in that.readValue) {
						messages.push({
							id: key,
							//value: 0,
							value: Array.isArray(this.readValue[key]) ? 0 : this.readValue[key],
							remark: ''
						})
					}
					that.$mqttTool.publish(
						`/${that.deviceInfo.productId}/${that.deviceInfo.serialNumber}/property/post`,
						JSON.stringify(messages), 'name')
				}
			},
			sendFirstToBle() {
				let that = this
				var state = getApp().globalData.bleObj.state;
				var deviceId = getApp().globalData.bleObj.deviceId;
				var isWrite = that.isWrite;
				if (state && deviceId != '' && isWrite === false && _self.isSendCmd === false) {
					that.readIndex = 0;
					that.isWrite = true;
					Protocol.writeStrToRead('0103a000002f2616', function(res) {
						console.log('sendFirstToBle');
						if (_self.isFirstLoad) {
							setTimeout(() => {
								_self.isFirstLoad = false
								that.$refs['collapse_1'].init()
								that.$refs['collapse_2'].init()
								that.$forceUpdate()
							}, 1000)
						}
					});
				}
			},
			//设置蓝牙请求数据
			SetValueChanged() {
				var that = this;
				//处理数据
				BLE.bleCallBack.CharacteristicValueChange = async function(res) {
					if (res != undefined && res != null && res != '') {
						if (_self.readIndex < 0) {
							that.isWrite = false
							console.log('蓝牙返回数据', res);
							console.log('发送指令成功');
							return
						}
						// console.log('蓝牙返回数据', res);
						var current = CMDs[that.readIndex];
						var packages = Protocol.solutionData(res);
						//console.log('蓝牙返回数据packages', packages);
						if (current && packages) {
							if (current.name === 'PACK') {
								//解析电池信息
								that.SetTargetVal(that.PackInfo, packages.data)
								let chStatus = that.PackInfo.Status.tValue ? that.PackInfo.Status.tValue.status *
									1 : 0;
								that.startChangeing(chStatus)

							}

							if (current.name === 'VCELL') {
								//解析电芯电压
								that.SetTargetVal(that.VCellInfo, packages.data)
							}

							if (current.name === 'TEMP') {
								//解析电池温度
								that.SetTargetVal(that.TempInfo, packages.data)
							}
							if (current.name === 'B_CONFIG') {
								that.SetTargetVal(that.B_CONFIG, packages.data)
							}
							if (current.name === 'VERSION') {
								//板子版本号
								_self.packVersion = hexToAscii(packages.data);
								//console.log('板子版本号packages', _self.packVersion);
							}

							that.readIndex++;
							if (that.readIndex > 3) {
								that.readIndex = 0;
							}
							setTimeout(() => {
								Protocol.writeStrToRead(CMDs[that.readIndex].cmd, function(res) {});
							}, 100)
						} else {
							that.isWrite = false
						}
					}
				}
			},
			/**
			 * 获取MQTT连接信息
			 */
			getMqttInfo(deviceId) {
				let that = this;
				let productCode = getApp().globalData.bleVersion
				that.$api.device.getMqttInfo(deviceId, productCode).then(res => {
					if (!res.data || !res.data.device) {
						return
					}
					console.log('获取产品ID', res.data);
					let device = res.data.device
					let mqttInfo = res.data.mqttInfo
					let info = {
						clientId: mqttInfo.clientId,
						username: mqttInfo.username,
						password: mqttInfo.passwd,
					}
					setTimeout(async () => {
						await this.connectMqtt(info)
						this.mqttSubscribe(device);
						this.mqttCallback();
					}, 100)
				})
			},
			async mqttSendOk(messages) {
				let that = this
				that.$mqttTool.publish(
					`/${that.deviceInfo.productId}/${that.deviceInfo.serialNumber}/property/post`,
					JSON.stringify(messages), '')
			},
			async mqttSendOTA(messages) {
				let that = this
				that.$mqttTool.publish(
					`/${that.deviceInfo.serialNumber}/http/upgrade/reply`,
					JSON.stringify(messages), '')
			},
			/* 断开Mqtt消息服务器 */
			async endMqtt() {
				await this.$mqttTool.end();
				this.sendEnable = false
			},
			/* 连接Mqtt消息服务器 */
			async connectMqtt(info) {
				let that = this
				if (this.$mqttTool.client === null) {
					if (info && info.username) {
						await this.$mqttTool.connect(info);
						this.$mqttTool.client.on('connect', function(res) {
							console.log('MQTT连接成功');
						});
					}
				}
			},
			/* Mqtt回调处理  */
			mqttCallback() {
				let that = this
				let topicArrs = [
					'/function/get',
					'/monitor/get',
					'/http/upgrade/set',
				]
				this.$mqttTool.client.on('message', async (topic, message, buffer) => {
					console.log('message:', message.toString());
					console.log('topic:', topic);

					let topics = topic.split('/');
					let str = '/' + topics[3] + '/' + topics[4];
					let productId = topics[1];
					let deviceNum = topics[2];
					that.deviceInfo = {
						productId: productId,
						serialNumber: deviceNum
					}
					message = JSON.parse(message.toString());
					if (!message) {
						return;
					};
					if (topic.includes(topicArrs[1])) {
						if (message.count * 1 > 0) {
							that.sendEnable = true
							setTimeout(() => {
								that.sendEnable = false
							}, message.count * 1000)
						} else {
							that.sendEnable = false
						}
						let name = getApp().globalData.bleObj.name
						utils.readListWithFilterExpire(name + "PROTECT").then(saveArr => {
							console.log('saveArr', saveArr);
							// 发送后台
							for (var i = 0; i < saveArr.length; i++) {
								let t = saveArr[i];
								t['productId'] = productId
								t['alertLevel'] = 3
								t['status'] = 1
								t['detail'] = ''
								saveAlertLog(t).then(res => {
									console.log('上传成功', res);
								})
							}
						})
					}

					if (topic.includes(topicArrs[0])) {
						for (var i = 0; i < message.length; i++) {
							let item = message[i]
							// console.log(item);
							let target = _self.allConfigParam[item.id]
							if (target) {
								let address = target.address
								// console.log('address', address);
								let v = parseFloat(item.value);
								if (!isNaN(v)) {
									console.log('v', v);
									_self.readIndex = -1
									Protocol.writeToWrite(address, Protocol.encryption(address, v),
										async () => {
											console.log('发送指令成功');
											await that.mqttSendOk([item])
										})
								}
							}
						}
					}

					if (topic.includes(topicArrs[2])) {
						const downFile = await downloadFile(message.url)
						console.log('downFile', downFile);
						let sendMessage = message
						sendMessage.progress = 0
						sendMessage.status = 2
						this.mqttSendOTA(sendMessage)
					}
				});
			},
			/** Mqtt订阅主题 */
			mqttSubscribe(device) {
				// 订阅当前设备状态和实时监测
				let topics = buildTopics(device);
				this.$mqttTool.subscribe(topics);
			},

			SetTargetVal(targetObj, valStr) {
				let targetKeys = Object.keys(targetObj)
				for (var i = 0; i < targetKeys.length; i++) {
					let key = targetKeys[i]
					let target = targetObj[key]
					target.value = valStr.substr(i * 4, 4);
					target.tValue = Protocol.algorithm(target.address, target.value)
					// let num = (parseInt(target.value, 16) - target.offset) * target.gain
					// const n = parseFloat(num);
					// const tValue = isNaN(n) ? num : n % 1 === 0 ? n : parseFloat(n.toFixed(1));
					// target.tValue = tValue;
					targetObj[key] = target
				}
			},
			toSettingPage() {
				uni.reLaunch({
					url: '/pages_ble/ble/tianyi/config'
				})
			},
		}
	}


	function downloadFile(fileUrl) {
		const url = projectConfig.baseUrl + fileUrl;
		console.log('下载文件url:', url);
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url, // 要下载文件的 URL
				success: (res) => {
					if (res.statusCode === 200) {
						console.log('下载成功', res.tempFilePath);
					} else {
						console.error('下载失败，状态码：', res.statusCode);
						uni.showToast({
							title: '下载失败',
							icon: 'error'
						});
					}
					resolve(res)
				},
				fail: (err) => {
					console.error('下载失败：', err);
					uni.showToast({
						title: '下载失败',
						icon: 'error'
					});
					resolve(err)
				}
			});
		})
	}

	/**
	 * MQTT主题订阅配置
	 * @param {Object} device 设备信息
	 */
	function buildTopics(device) {
		let topics = [];
		let preUrl = '/' + device.productId + '/' + device.serialNumber;
		// 订阅当前设备状态和实时监测
		let functionGet = preUrl + '/function/get';
		let topicInfo = preUrl + '/info/get';
		let topicMonitor = preUrl + '/monitor/get';
		let topicOta = '/' + device.serialNumber + '/http/upgrade/set';
		topics.push(functionGet);
		topics.push(topicInfo);
		topics.push(topicMonitor);
		topics.push(topicOta);
		return topics
	}

	function hexToAscii(hexStr) {
		let asciiStr = '';
		for (let i = 0; i < hexStr.length; i += 2) {
			const byte = hexStr.substr(i, 2);
			const charCode = parseInt(byte, 16);
			if (charCode < 0x20 || charCode > 0x7E) {
				// 控制字符或非 ASCII 字符，显示为 \xHH
				asciiStr += `\\x${byte}`;
			} else {
				// 可打印 ASCII 字符
				asciiStr += String.fromCharCode(charCode);
			}
		}
		return asciiStr;
	}
</script>

<style lang="scss" scoped>
	.bg-white {
		background-color: rgb(255 255 255 / 60%);
	}


	.warp {
		color: #404e75;
		min-height: 100vh;
		background-size: cover;
		background-attachment: fixed;
	}

	.container {
		overflow: auto;
		height: 100vh;
		width: 100%;
		position: absolute;
		background-color: rgb(255 255 255 / 0%);
		top: 0%;
		left: 0%;
	}

	.b-card {
		background-color: #FFFFFF;
		border-radius: 18rpx;
		box-shadow: 2rpx 2rpx 4rpx 4rpx #def4f9;
	}
</style>


<style lang="scss" scoped>
	.radius-25 {
		border-radius: 15rpx;
	}
</style>